//
// Copyright 2022 The Sparrow Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "sparrow/time.h"

#include <time.h>

#ifdef _WIN32
#include <Windows.h>
#include <processthreadsapi.h>
#include <sys/types.h>
#include <sys/timeb.h>
#else
#include <unistd.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <fcntl.h>
#include <errno.h>
#endif

extern "C" {

#ifdef _WIN32
static LARGE_INTEGER g_start_time;
static double g_time_scale;

void sp_time_init() {
    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    QueryPerformanceCounter(&g_start_time);
    g_time_scale = 1.0 / (double)frequency.QuadPart;
}

void sp_system_clock(struct sp_time_sepc_t *ts) {
    struct _timeb tb;
    _ftime_s(&tb);
    ts->tv_sec = (int64_t)tb.time;
    ts->tv_nsec = tb.millitm * 1000 * 1000;
}
void sp_steady_clock(struct sp_time_sepc_t *ts) {
    LARGE_INTEGER performance_count;
    QueryPerformanceCounter(&performance_count);
    LONGLONG diff = performance_count.QuadPart - g_start_time.QuadPart;
    double value = (double)diff * g_time_scale;
    ts->tv_sec = (int64_t)value;
    ts->tv_nsec = (int32_t)((value - (double)tv_sec) * 1e9);
}
#else
void sp_time_init() {}
void sp_system_clock(struct sp_time_sepc_t *ts) {
    struct timespec temp;
    clock_gettime(CLOCK_REALTIME, &temp);
    ts->tv_sec = temp.tv_sec;
    ts->tv_nsec = temp.tv_nsec;
}
void sp_steady_clock(struct sp_time_sepc_t *ts) {
    struct timespec temp;
    clock_gettime(CLOCK_MONOTONIC, &temp);
    ts->tv_sec = temp.tv_sec;
    ts->tv_nsec = temp.tv_nsec;
}
#endif // _WIN32

int sp_format_time(const char *fmt, char buff[32]) {
    time_t timer = time(NULL);

    struct tm stm;

#if defined(_WIN32)
    localtime_s(&stm, &timer);
#else
    localtime_r(&timer, &stm);
#endif

    // "%F %T" 2020-05-10 01:43:06
    char buff[64] = {0};

    return (int)strftime(buff, sizeof(buff), fmt, &stm);
}
} // extern "C"
